﻿using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Specifications;
using AppFramework.DinosaursParkMes.CodingRuleModel;
using AppFramework.DinosaursParkMes.Dictionaries;
using AppFramework.DinosaursParkMes.DictionariesModel;
using AppFramework.DinosaursParkMes.DomainService.CodingRule;
using AppFramework.DinosaursParkMes.MaterialModel;
using AppFramework.DinosaursParkMes.Product.DTO;
using AppFramework.Dto;
using AutoMapper;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Minio.DataModel;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using NUglify.JavaScript.Syntax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RouteAttribute = Microsoft.AspNetCore.Mvc.RouteAttribute;


namespace AppFramework.DinosaursParkMes.Product
{
    /// <summary>
    /// 产品管理
    /// </summary>
    public class ProductinfoAppService : AppFrameworkAppServiceBase, IProductinfoAppService
    {
        private readonly IRepository<Productinfo> repository;
        private readonly IRepository<ProductClassification> ProductClassrepository;
        private readonly IRepository<MaterialProductImg> MaterialProductImgrepository;
        private readonly ICodingruleManager _manager;

        public ProductinfoAppService(IRepository<Productinfo> repository = null, IRepository<ProductClassification> productClassrepository = null, IRepository<MaterialProductImg> materialProductImgrepository = null, ICodingruleManager manager = null)
        {
            this.repository = repository;
            ProductClassrepository = productClassrepository;
            MaterialProductImgrepository = materialProductImgrepository;
            _manager = manager;
        }
        /// <summary>
        /// 产品添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost,Route("InsertProduct")]
        [UnitOfWork]
        public async Task<int> InsertProduct([FromBody]ProductRequestDTO dto)
        {
            var productmodel = ObjectMapper.Map<Productinfo>(dto);
            productmodel.Productid =await _manager.GetCode("Productinfo"); //"CP" + DateTime.Now.ToString("yyyyMMddhhmmss");
            await repository.InsertAsync(productmodel);
            foreach (var item in dto.ImgChildren)
            {
                var productimagemodel = ObjectMapper.Map<MaterialProductImg>(item);
                productimagemodel.Filetype = 1;
                productimagemodel.Number = productmodel.Productid;
                await MaterialProductImgrepository.InsertAsync(productimagemodel);
            }
            foreach (var item in dto.AccessoryChildren)
            {
                var attachmentmodel = ObjectMapper.Map<MaterialProductImg>(item);
                attachmentmodel.Filetype = 0;
                attachmentmodel.Number = productmodel.Productid;
                await MaterialProductImgrepository.InsertAsync(attachmentmodel);
            }
            return 1;
        }
        /// <summary>
        /// 产品反填
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet,Route("SelectProductById")]
        public async Task<ResultResponseDTO<ProductSelectDTO>> SelectProductById(int id)
        {
            ResultResponseDTO<ProductSelectDTO> dto=new ResultResponseDTO<ProductSelectDTO>();
            var images = MaterialProductImgrepository.GetAll();
            var list = from a in repository.GetAll()
                       join b in ProductClassrepository.GetAll() on a.Productclassid equals b.Id
                       where a.Id == id
                       select new ProductSelectDTO
                       {
                           Id = a.Id,
                           Classname = b.Classname,
                           Date = a.Date,
                           Inventoryceiling = a.Inventoryceiling,
                           Numberday = a.Numberday,
                           Periodofvalidity = a.Periodofvalidity,
                           Productclassid = a.Productclassid,
                           Productid = a.Productid,
                           Productname = a.Productname,
                           Productproperty = a.Productproperty,
                           Producttype = a.Producttype,
                           Purchaseprice = a.Purchaseprice,
                           Remark = a.Remark,
                           Saleprice = a.Saleprice,
                           Specification = a.Specification,
                           State = a.State,
                           Stockfloor = a.Stockfloor,
                           Units = a.Units,
                           CreatorUserId = a.CreatorUserId,
                           CreationTime = a.CreationTime,
                           images = (from x in images where a.Productid == x.Number select new ProductImgList
                                   {
                                       Filepath=x.Filepath
                                   }).ToList(),
                           attachment= (from x in images
                                        where a.Productid == x.Number
                                        select new AttachmentList
                                        {
                                            Filename=x.Filename,
                                            Filepath=x.Filepath
                                        }).ToList(),
                       };
            //var dto = repository.GetAllList().Where(m => m.Id == id).FirstOrDefault();
            //return ObjectMapper.Map<ProductSelectDTO>(list);
            dto.Code = ResponsCode.Succsee;
            dto.Data = list.ToList().FirstOrDefault();
            return dto;
        }

        /// <summary>
        /// 显示产品
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet,Route("ShowProduct")]
        public async Task<PagedResultDto<ProductResponseDTO>> ShowProduct(ProductChaDTO dto)
        {
            PagedResultDto<ProductResponseDTO> dtos = new PagedResultDto<ProductResponseDTO>();

            var list = from a in  repository.GetAll()
                       join b in  ProductClassrepository.GetAll() on a.Productclassid equals b.Id
                       select new ProductResponseDTO
                       {
                           Id = a.Id,
                           Productid = a.Productid,
                           Productname = a.Productname,
                           Specification = a.Specification,
                           Units = a.Units,
                           Producttype = a.Producttype,
                           Productproperty = a.Productproperty,
                           Classname = b.Classname,
                           State = a.State,
                           Productclassid = a.Productclassid,
                       };
            if(!string.IsNullOrEmpty(dto.productid))
            {
                list = list.Where(m=>m.Productid.Equals(dto.productid) || m.Productname.Equals(dto.productid));
            }
            if(!string.IsNullOrEmpty(dto.producttype))
            {
                list = list.Where(m=>m.Producttype.Equals(dto.producttype));
            }
            if(dto.state!=-1)
            {
                list = list.Where(m=>m.State==dto.state);
            }
            if(!string.IsNullOrEmpty(dto.productproperty))
            {
                list = list.Where(m=>m.Productproperty.Equals(dto.productproperty));
            }
            if(dto.productclassid!=-1)
            {
                list = list.Where(m=>m.Productclassid==dto.productclassid);
            }
            dtos.TotalCount= list.Count();
            dtos.Items=await list.OrderByDescending(p => p.Id).Skip((dto.pageindex - 1) * dto.pagesize).Take(dto.pagesize).ToListAsync();;
            return dtos;
        }
    }
}
